package com.central.apps.handler;

import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 位置管理
 */
@Component
public class locationmanagementHabdler extends LvBaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        String id = MapUtils.getString(data,"id");
        String parent = MapUtils.getString(data,"parent");
        String parents = MapUtils.getString(data,"parents");
        String location = MapUtils.getString(data,"location");
        //新增的时候
        if(StringUtils.isNotEmpty(parent) && StringUtils.isNotEmpty(parents) && !parents.contains("'" + parent + "'")) {
            //不等于空就说明是子级
            //拿到他的所有父级
            List<Map<String, Object>> mapList = handlerService.findBySql("select PARENTS from bl_locationmanagement where location = '" + parent + "' ");
            if(CollectionUtils.isNotEmpty(mapList)){
                String newParents = MapUtils.getString(mapList.get(0),"PARENTS") + ",'" + location + "'";
                data.put("PARENTS",newParents);
                //更新下面所有子级包括父级 吧parents 替换成 newParents 注意只是一部分替换 再后面的子级不替换
                //update t_user set nick_name=replace(nick_name,'需要替换的值','替换后的值')
                //又因为值中有单引号所以sql中字符串用双引号
                handlerService.updateBySql("update bl_locationmanagement set PARENTS = replace(PARENTS,\"" + parents + "\",\"" + newParents  + "\") where PARENTS like \"%" + parents + "%\";");
            }
        }else{
            if(StringUtils.isEmpty(id) || StringUtils.isEmpty(parent)){
                data.put("PARENTS","'" + location + "'");
            }
        }
    }

}
